package xyz.xtgl.oauth2.service;

import common.core.dto.LoginUserDto;
import common.core.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import xyz.xtgl.merchant.entity.BMerchantUser;
import xyz.xtgl.merchant.feign.BMerchantUserFeign;
import xyz.xtgl.oahth2.config.constant.GlobalConstant;

@Service
public class CustomUserDetailsService implements  UserDetailsService{

    @Autowired
    private BMerchantUserFeign bMerchantUserFeign;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UsernamePasswordAuthenticationToken upat = (UsernamePasswordAuthenticationToken)authentication;
        User user = (User) upat.getPrincipal();
        UserDetails userDetails = null;
        if(GlobalConstant.XTGL_WEB_CLIENT_ID_MERCHANT.equals(user.getUsername())){
            BMerchantUser bean = bMerchantUserFeign.loginByPhone(username);
            if(CommonUtil.isEmpty(bean)){
                throw new UsernameNotFoundException("用户名不存在");
            }
            LoginUserDto dto = new LoginUserDto();
            dto.setId(bean.getId());
            dto.setUsername(username);
            dto.setName(bean.getContactName());
            userDetails = User .withUsername(CommonUtil.convertObjectToJson(dto)).password(bean.getPassword()).authorities(new String[]{}).build();
        }else{
            throw new UsernameNotFoundException("未知的服务");
        }

        return userDetails;
    }
}